package cn.itcast.bos.web.action.take_delivery;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;
import cn.itcast.bos.utils.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

@Namespace("/")
@ParentPackage("json-default")
@Scope("protoType")
@Controller
public class WayBillAction extends BaseAction<WayBill> {
    @Autowired
    private WayBillService wayBillService;
    @Action(value="save_waybill",results = {@Result(name="success",type = "json")})
    public String saveWayBill_quick(){
        //判断order是否有id,如果没有,设置order为null
        if(model.getOrder() !=null &&(model.getOrder().getId()==null ||model.getOrder().getId()==0)){
            model.setOrder(null);
        }
        //建立一个集合,将返回的数据存储起来
        Map<String,Object> result = new HashMap<>();
        try{
            wayBillService.save(model);
            result.put("success",true);
            result.put("msg","保存运单成功");

        }catch(Exception e){
            e.printStackTrace();
            result.put("success",false);
            result.put("msg","保存运单失败");

        }
        //将结果压入值栈
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }
    //分页查询
    @Action(value = "findAll_WayBill",results = {@Result(name="success",type = "json")})
    public String findAllWayBill(){
        Pageable pageable = new PageRequest(page-1,rows, Sort.Direction.DESC,"id");
        Page<WayBill> pageData = wayBillService.findAll( model,pageable);
        //压入值栈
        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }
    //根据运单号查询运单的方法
    @Action(value = "findByWayBillNum",results = {@Result(name="success",type="json")})
    public String findByWayBillNum(){
        WayBill WayBill = wayBillService.findByWayBillNum(model.getWayBillNum());
        Map<String,Object> result = new HashMap<>();
        if(WayBill == null){
            result.put("success",false);
        }else{
            result.put("success",true);
            result.put("wayBillData",WayBill);
        }
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }
}
